<template>
  <div
    v-if="isVisible"
    :style="{ top: y + 'px', left: x + 'px' }"
    class="select-menu absolute bg-white shadow-md rounded-[12px] p-[8px] z-contextMenu"
    ref="contextMenu"
  >
    <div
      v-for="(item, index) in contextMenuStore.contextMenu"
      :key="index"
      class="mb-[4px] px-[12px] h-[32px] leading-[32px] hover:bg-gray-100 cursor-pointer rounded-[6px] text-[14px]"
      @click.stop="contextMenuClick(item.value)"
    >
      {{ item.label }}
      <!-- <span v-if="item.shortcut" class="float-right text-gray-500 text-sm">
          {{ item.shortcut }}
        </span> -->
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watchEffect, watch, nextTick } from "vue";
import { useContextMenuStore } from "../store";

const isVisible = ref(false);
const x = ref(0);
const y = ref(0);

// const props = defineProps(["menuItems"]);
const contextMenuStore = useContextMenuStore();

const closeContextMenu = () => {
  // if (!isVisible.value) {
  // }

  isVisible.value = false;
  contextMenuStore.setMenuActive("");
  if (contextMenuStore.menuActive === "") {
    document.removeEventListener("click", closeContextMenu);
  }
};

const contextMenu = ref<HTMLElement | null>(null);

watch(
  () => [contextMenuStore.position.x, contextMenuStore.position.y],
  () => {
    isVisible.value = true;
    nextTick(() => {
      if (contextMenu.value) {
        const { offsetWidth, offsetHeight } = contextMenu.value as HTMLElement;
        const { innerWidth, innerHeight } = window;
        let posX = contextMenuStore.position.x;
        let posY = contextMenuStore.position.y;
        if (posX + offsetWidth > innerWidth) {
          posX = innerWidth - offsetWidth - 6;
        }
        if (posY + offsetHeight > innerHeight) {
          posY = innerHeight - offsetHeight - 6;
        }
        x.value = posX;
        y.value = posY;
      }
    });

    document.addEventListener("click", closeContextMenu);
  }
);

const emits = defineEmits(["contextMenuClick"]);
const contextMenuClick = (item) => {
  contextMenuStore.setMenuActive(item);
  isVisible.value = false;
};
</script>
<style scoped></style>
